package com.kevin.utility.common;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class XssFilter implements Filter {

	public void destroy() {		
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req= (HttpServletRequest)request;
	    //HttpServletResponse res = (HttpServletResponse)response;	    
		
	    boolean ifXss=false;
	    
		Map map = new HashMap();
		map = req.getParameterMap();
        for(Object key: map.keySet().toArray()){ 
        	String paraValue = ((String[])map.get(key))[0];
        	String tmpParaValue = paraValue.replace(" ", "");
        	if(tmpParaValue.indexOf("<script>")>-1){
        		ifXss=true;
        		break;
        	}
        	
        	Pattern p = Pattern.compile("<.*=.*\\son.*=.*>");//miibeian.*?>(.*?)<
        	Matcher m = p.matcher(paraValue);//"<a href=http://www.miibeian.gov.cn target=_blank>京ICP证030173号</a>"
        	if(m.find()){
        		ifXss=true;
        		break;
        	}
        } 
        
        if(ifXss){
        	//不能跳转，需填坑
        	//res.sendRedirect(req.getContextPath()+"/error.jsp");
        }else{
    		chain.doFilter(request, response);
    	}	
	}

	public void init(FilterConfig arg0) throws ServletException {
				
	}

}
